﻿using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.Context;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.HttpUtility;
using Senparc.Weixin.MP.MessageHandlers;

namespace Weixin.Sample
{
    public partial class WMessageHandler : MessageHandler<MessageContext>
    {
        public WMessageHandler(Stream inputStream, int maxRecordCount = 0)
            : base(inputStream, maxRecordCount)
        {
            WeixinContext.ExpireMinutes = 3;
        }

        /// <summary>
        /// 文本请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            if (requestMessage.Content.Contains("天气"))
            {
                var response = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage);
                response.ArticleCount = 5;              
                string city = requestMessage.Content.Replace("天气", string.Empty).Trim();
                response.Articles.Add(new Article { Title = city + "天气预报" });

                string url = string.Format(Utitly.WeatherService, city);
                string jsonVav = RequestUtility.HttpGet(url, System.Text.Encoding.UTF8);

                JObject j = JObject.Parse(jsonVav);
                JArray jr = j["results"][0]["weather_data"] as JArray;
                response.Articles.AddRange(jr.Select(x =>
                {
                    return new Article
                    {
                        PicUrl = x.Value<string>("dayPictureUrl"),
                        Title = x.Value<string>("date") + System.Environment.NewLine
                            + x.Value<string>("weather") + "  "
                            + x.Value<string>("wind") + "  "
                            + x.Value<string>("temperature"),
                    };
                }));

                return response;
            }

            if (requestMessage.Content.Contains("翻译"))
            {
                var response = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
                string word = requestMessage.Content.Replace("翻译", string.Empty).Trim();
                string url = string.Format(Utitly.YoudaoService, word);
                string jsonVav = RequestUtility.HttpGet(url, System.Text.Encoding.UTF8);              

                System.Text.StringBuilder sb = new System.Text.StringBuilder(word);
                sb.AppendLine();
                JToken jtoken = JToken.Parse(jsonVav);

                sb.AppendLine("---有道翻译---").AppendLine(jtoken.Value<JArray>("translation")[0].Value<string>());

                try
                {
                    JArray basicexplains = jtoken.Value<JToken>("basic").Value<JArray>("explains");
                    sb.AppendLine("---基本含义---");
                    foreach (JToken be in basicexplains)
                    {
                        sb.AppendLine(be.Value<string>());
                    }

                    JToken aweb = jtoken.Value<JArray>("web")[0].Value<JArray>("value");
                    sb.AppendLine("---网络释义---");
                    foreach (JToken aaweb in aweb)
                    {
                        sb.AppendLine(aaweb.Value<string>());
                    }
                }
                catch { }

                response.Content = sb.ToString();
                return response;
            }

            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            string curl = string.Format(Utitly.ChongdongService, requestMessage.Content);
            string cjsonVav = RequestUtility.HttpGet(curl, System.Text.Encoding.UTF8);

            JToken jt = JToken.Parse(cjsonVav);
            if (jt.Value<int>("code") == 40006)
            {
                responseMessage.Content =
                    string.Format(
                        "您刚才发送了文字信息：{0}" + System.Environment.NewLine
                        + "发送【天气地名】就可以获得未来地名四天的天气情况" + System.Environment.NewLine
                        + "发送【翻译内容】就可以获得相应翻译后的结果" + System.Environment.NewLine
                        + "发送【笑话】获得一条笑话" + System.Environment.NewLine
                        + "我们已记录您的需求，后续会添加",
                        requestMessage.Content);
            }
            else
            {
                responseMessage.Content = jt.Value<string>("text");
            }       

            return responseMessage;
        }

        /// <summary>
        /// 位置请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnLocationRequest(RequestMessageLocation requestMessage)
        {
            LocationService lservice = new LocationService();
            return lservice.GetResponseMessage(requestMessage);
        }

        /// <summary>
        /// 链接请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnLinkRequest(RequestMessageLink requestMessage)
        {
            return base.OnLinkRequest(requestMessage);
        }

        /// <summary>
        /// 视频请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage)
        {
            return base.OnVideoRequest(requestMessage);
        }

        /// <summary>
        /// 声音请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVoiceRequest(RequestMessageVoice requestMessage)
        {
            return base.OnVoiceRequest(requestMessage);
        }

        /// <summary>
        /// 图片请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnImageRequest(RequestMessageImage requestMessage)
        {
            return base.OnImageRequest(requestMessage);
        }

        public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
        {
            var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(requestMessage);
            responseMessage.Content = "相关功能正在完善,我们已收录您的相关要求";
            return responseMessage;
        }
    }
}